package com.zl.cms.web;

import com.zl.basic.model.SystemContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-22 Time: 上午10:30
 */
public class SystemContextFilter implements Filter {
  private Integer pageSize;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    try {
      pageSize = Integer.parseInt(filterConfig.getInitParameter("pageSize"));
    } catch (NumberFormatException e) {
      pageSize = 15;
    }
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Integer offset = 0;
    try {
      offset = Integer.parseInt(request.getParameter("pager.offset"));
    } catch (NumberFormatException e) {}
    try {
      SystemContext.setOrder(request.getParameter("order"));
      SystemContext.setSortkey(request.getParameter("sort"));
      SystemContext.setPageOffset(offset);
      SystemContext.setPageSize(pageSize);
      SystemContext.setRealPath(((HttpServletRequest) request).getSession().getServletContext()
          .getRealPath("/"));
      chain.doFilter(request, response);
    } finally {
      SystemContext.removeOrder();
      SystemContext.removeSortKey();
      SystemContext.removePageSize();
      SystemContext.removePaseOffset();
      SystemContext.removeRealPath();
    }

  }

  @Override
  public void destroy() {

  }
}
